package cn.john.hrm.service.impl;

import cn.john.hrm.LoginUserConstant;
import cn.john.hrm.domain.Employee;
import cn.john.hrm.domain.LoginUser;
import cn.john.hrm.domain.Tenant;
import cn.john.hrm.dto.EnteringDto;
import cn.john.hrm.feign.LoginUserFeignClient;
import cn.john.hrm.mapper.EmployeeMapper;
import cn.john.hrm.mapper.TenantMapper;
import cn.john.hrm.query.TenantQuery;
import cn.john.hrm.service.ITenantService;
import cn.john.hrm.util.AjaxResult;
import cn.john.hrm.util.PageList;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author john
 * @since 2021-06-17
 */
@Service
public class TenantServiceImpl extends ServiceImpl<TenantMapper, Tenant> implements ITenantService {
    @Autowired
    private TenantMapper tenantMapper;

    @Autowired
    private EmployeeMapper employeeMapper;

    // 注入feign对象
    @Autowired
    private LoginUserFeignClient client;

    @Override
    public AjaxResult loadPageList(TenantQuery query) {
        // 构造分页对象
        Page<Tenant> page = new Page<Tenant>(query.getPage(),query.getRows());
        // 查询列表
        List<Tenant> list = tenantMapper.loadPageList(page,query);
        // 将查询的结果封装成一个分页对象
        PageList<Tenant> pageList = new PageList<>(page.getTotal(), list);
        // 返回
        return AjaxResult.me().setResultObj(pageList);
    }

    @Override
    public AjaxResult entering(EnteringDto dto) {
        // 调用auth服务，保存loginUser信息以及套餐
        LoginUser loginUser = new LoginUser();
        // 获取employee信息封装一个loginUser
        Employee employee = dto.getEmployee();
        loginUser.setUsername(employee.getUsername());
        loginUser.setPassword(employee.getPassword());
        loginUser.setType(LoginUserConstant.LOGIN_USER_ADMIN);
        loginUser.setMealId(dto.getMealId());
        AjaxResult result = client.addOrUpdate(loginUser);
        if(!result.isSuccess()) {
            throw new RuntimeException("套餐保存异常，请重新操作!");
        }
        // 获取保存以后的loginUserid
        Integer id = (Integer) result.getResultObj();
        Long loginUserId = Long.valueOf(id);
        // 保存机构基本信息
        Tenant tenant = dto.getTenant();
        Date date = new Date();
        tenant.setRegisterTime(date);
        tenantMapper.insert(tenant);
        // 保存机构管理员信息 tenantId loginUserId
        employee.setTenantId(tenant.getId());
        employee.setLoginId(loginUserId);
        employee.setInputTime(date);
        employee.setState(0);
        employee.setType(LoginUserConstant.LOGIN_USER_ADMIN);
        employeeMapper.insert(employee);
        return AjaxResult.me();
    }
}
